package com.telecom.at.front;

import java.io.File;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.telecom.at.db.dac.Dac;
import com.telecom.at.db.model.Doc;
//import com.telecom.llyc.db.model.User;

@WebServlet("/front/UploadDoc2")
@MultipartConfig
public class UploadDoc2 extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.getRequestDispatcher("/WEB-INF/jsp/front/DragUploadDoc.jsp").forward(request, response);
	}
    private String getFilename(Part part) {
        String contentDispositionHeader = 
                part.getHeader("content-disposition");
        String[] elements = contentDispositionHeader.split(";");
        for (String element : elements) {
            // System.out.println(element);
            if (element.trim().startsWith("filename")) {
                String fileName = element.substring(element.indexOf('=') + 1)
                        .trim().replace("\"", "");
                return new File(fileName).getName();
            }
        }
        return null;
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Map<String, String> inputMap = new HashMap<String, String>();
        Map<String, String> errorMap = new HashMap<String, String>();
        request.setAttribute("input", inputMap);
        request.setAttribute("error", errorMap);
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=UTF-8");
        boolean success = false;
        Part part = request.getPart("file");
        String fileName = getFilename(part);
        if(fileName == null || fileName.isEmpty()) {
            errorMap.put("file", "鐠囩兘锟藉瀚ㄧ憰浣风瑐娴肩姷娈戦弬鍥︽");
        }
        if (errorMap.size() == 0) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String uriPath = "/WEB-INF/file/upload/"+sdf.format(new Date());
            String physicalPath = getServletContext().getRealPath(uriPath);
            if(! new File(physicalPath).exists()) {
                new File(physicalPath).mkdirs();
            }
            physicalPath += File.separator;
            String fn = UUID.randomUUID().toString();
            physicalPath += fn;
            uriPath += "/"+ fn;
            System.out.println(physicalPath);
            //System.out.println(uriPath);
            part.write(physicalPath);
            Doc doc = new Doc();
            doc.setName(fileName);
            doc.setFullName(uriPath);
            doc.setUploadedTime(new Timestamp(new java.util.Date().getTime()));
            //User curUser = (User)request.getSession().getAttribute("curUser");
            //doc.setUserId(curUser.getId());
            doc.setUserId(0); // 姒涙顓绘担璺ㄦ暏0閻€劍鍩�
            
            Dac.getInstance().addDoc(doc);
            if(doc.getId()>0) {
                success = true;
                //response.sendRedirect("ListDoc");
                response.getWriter().write("File " + fileName + " successfully uploaded");
            }else {
                errorMap.put("error", "娑撳﹣绱舵径杈Е");
            }
        }
        if (!success)
            request.getRequestDispatcher("/WEB-INF/jsp/front/UploadDoc.jsp").forward(request, response);
    }
}
